<template>
  <div class="waterfall-grid">
    <div v-for="(item, index) in postList" :key="index" class="container">
      <div class="image-wrapper">
        <video v-if="item.postPhoto.split('.').pop()==='mp4'" :src="item.postPhoto" controls @click="commentDetails(item)" />
        <img v-else :src="item.postPhoto" alt="图片" @click="commentDetails(item)">
        <span class="title">{{ item.postTitle }}</span>&nbsp;
        <span v-if="item.examine===0" class="title">未审核</span>
        <span v-else-if="item.examine===1" class="title">审核通过</span>
        <span v-else-if="item.examine===2" class="title">审核不通过</span>
        <span v-else-if="item.examine===3" class="title">被举报</span>
      </div>
      <div class="user-info">
        <img class="user-icon" :src="item.photo" alt="�û�ͼ��">
        <span>{{ item.name }}</span>
        <el-button @click="changePost(item)"> 修改</el-button>
        <el-button @click="deletePost(item)"> 删除</el-button>
        <div class="checkbox-wrapper">
          <input id="like-checkbox" v-model="item.isPraise" type="checkbox" class="checkbox">
          <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="heart-icon" @click="praisePost(item)">
            <path :d="heartPath" :fill="item.isPraise ? 'red' : 'gray'" />
          </svg>
          <span class="like-count">{{ item.postPraise }}</span>
        </div>
      </div>
    </div>
    <blog-detall ref="postDetails" />
    <el-dialog :visible.sync="dialogVisible">
      <el-form ref="form" :model="theitem" label-width="80px" class="demo-ruleForm">
        <el-form-item prop="postPhoto">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8081/common/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <div v-if="theitem.postPhoto" slot="default">
              <video v-if="isVideo(theitem.postPhoto)" :src="theitem.postPhoto" controls style="width: 400px;" />
              <img v-else :src="theitem.postPhoto" alt="主图片" style="width: 400px;">
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="postTitle">
          <el-input v-model="theitem.postTitle" />
        </el-form-item>
        <el-form-item label="内容" prop="postContent">
          <el-input v-model="theitem.postContent" />
        </el-form-item>
        <el-form-item label="标签" prop="labelList">
          <el-checkbox v-for="item in label" :key="item.labelId" v-model="checkLabel" :label="item.labelId">
            {{ item.labelName }}
          </el-checkbox>
        </el-form-item>
        <el-button type="primary" @click="submitForm(theitem)">立即发布</el-button>
      </el-form>
    </el-dialog>
    <blog-detall ref="postDetails" @commentDetails="commentDetails" />
  </div>
</template>
<script>
import { deleteAction, getAction, postAction } from '@/utils/xhs-ajax'
import blogDetall from '@/views/userHome/components/detall/myBlogDetail.vue'
import item from '@/layout/components/Sidebar/Item.vue'

export default {
  components: {
    blogDetall
  },
  data() {
    return {
      imageUrl: '',
      label: [],
      checkLabel: [], // 选中的标签
      theitem: {
        postId: '',
        userId: '',
        postTitle: '',
        postContent: '',
        postPhoto: '',
        labelList: []
      },
      dialogVisible: false,
      postList: [],
      heartPath: 'M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z' // ����ͼ���·������
    }
  },
  computed: {
    item() {
      return item
    },
    displayedImage() {
      return this.imageUrl || this.theitem.postPhoto
    }
  },
  created() {
    this.getPostList()
    this.getlabelList()
  },
  methods: {
    praisePost(item) {
      var id = item.postId
      item.isPraise = !item.isPraise
      if (item.isPraise) {
        item.postPraise++
      } else {
        item.postPraise--
      }
      postAction('/post/praisePost.do', { postId: id }).then(resp => {
        this.getPostList()
      })
    },
    getPostList() {
      getAction('/post/checkUserPost.do', {}).then(resp => {
        this.postList = resp.data
      })
    },
    commentDetails(item) {
      getAction('/post/commentDetails.do?postId=' + item.postId, {}).then(resp => {
        this.$refs.postDetails.commentList = resp.data
      })
      this.$refs.postDetails.dialogVisible = true
      this.$refs.postDetails.post = item
    },
    changePost(item) {
      this.dialogVisible = true
      this.theitem = item
      this.checkLabel = item.labelList.map(label => label.labelId)
      console.log(this.checkLabel)
    },
    deletePost(item) {
      this.$confirm('是否删除?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAction('/administrators/deletePost', item.postId).then(resp => {
          alert('删除成功！')
          this.reset()
        }).catch(error => {
          alert('删除失败：' + error.message)
        })
      }).catch(() => {
        // 用户取消删除
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    reset() {
      this.getPostList()
    },
    submitForm(theitem) {
      const selectedLabels = this.checkLabel.map(labelId => {
        const label = this.label.find(l => l.labelId === labelId)
        return label ? { labelId: label.labelId, labelName: label.labelName } : null
      }).filter(Boolean)
      this.theitem.labelList = selectedLabels
      postAction('/post/updateUserPost.do', this.theitem).then(resp => {
        if (resp.code === 200) {
          this.$message.success('修改成功!')
          this.dialogVisible = false
          this.getPostList()
        } else {
          this.$message.error(resp.msg)
        }
      })
    },
    getlabelList() {
      getAction('/post/getLabel.do').then(resp => {
        this.label = resp.data
      })
    },
    handleAvatarSuccess(res, file) {
      console.log('res:', res)
      console.log('file.raw:', file.raw) // 检查 file.raw 是否有效
      this.imageUrl = URL.createObjectURL(file.raw)
      this.file = file.raw
      this.theitem.postPhoto = res.data
    },
    beforeAvatarUpload(file) {
      const allowedTypes = ['image/jpeg', 'image/png', 'image/pdf', 'video/mp4']
      const isJPG = allowedTypes.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 20

      if (!isJPG) {
        this.$message.error('上传文件片格式有误!')
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 20MB!')
      }
      return isJPG && isLt2M
    },
    isVideo(file) {
      if (!file) return false // 确保 file 不为空
      const ext = file.split('.').pop().toLowerCase()
      return ['mp4', 'avi', 'mov'].includes(ext)
    },
    handleCheckboxChange(item, isChecked) {
      const labelId = item.labelId
      if (isChecked) {
        this.checkLabel.push(labelId)
      } else {
        this.checkLabel = this.checkLabel.filter(id => id !== labelId)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.waterfall-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 10px;
}

:root {
  --main-border-color: #ccc;
  --margin-size: 10px;
}

.container {
  width: 300px;
  height: auto;
  border: 1px solid var(--main-border-color);
  padding: var(--margin-size);
  box-sizing: border-box;
}

.image-wrapper img {
  width: 300px;
  height: 300px;
  border-bottom: 1px solid var(--main-border-color);
  margin-bottom: var(--margin-size);
  border-radius: 5%;
}

.image-wrapper video {
  width: 300px;
  height: 300px;
  border-bottom: 1px solid var(--main-border-color);
  margin-bottom: var(--margin-size);
  border-radius: 5%;
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: var(--margin-size);
}

.user-info {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: var(--margin-size);
}

.user-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 5px;
}

.user-info span {
  font-size: 14px;
}

.checkbox-wrapper {
  position: relative;
  display: inline-block;
  margin-left: auto;
}

.checkbox-wrapper input[type="checkbox"] {
  display: none;
}

.heart-icon {
  cursor: pointer;
}

.like-count {
  font-size: 14px;
  color: #888;
  margin-left: 5px;
}
</style>
